/**
 * 设置页面脚本 - 图片视频下载器
 * 负责处理设置页面的交互和数据管理
 */

// 全局变量
let currentSettings = {};
let hasUnsavedChanges = false;

/**
 * 设置页面管理器类
 */
class OptionsManager {
    constructor() {
        this.isInitialized = false;
    }

    /**
     * 初始化设置页面
     */
    async init() {
        if (this.isInitialized) return;

        console.log('初始化设置页面...');

        // 绑定事件监听器
        this.bindEvents();

        // 加载设置
        await this.loadSettings();

        // 更新存储使用情况
        await this.updateStorageInfo();

        this.isInitialized = true;
        console.log('设置页面初始化完成');
    }

    /**
     * 绑定事件监听器
     */
    bindEvents() {
        // 导航菜单
        document.querySelectorAll('.nav-item').forEach(item => {
            item.addEventListener('click', (e) => {
                e.preventDefault();
                this.switchSection(item.dataset.section);
            });
        });

        // 保存按钮
        document.getElementById('saveBtn').addEventListener('click', () => {
            this.saveSettings();
        });

        // 重置按钮
        document.getElementById('resetBtn').addEventListener('click', () => {
            this.resetSettings();
        });

        // 数据操作按钮
        document.getElementById('exportDataBtn').addEventListener('click', () => {
            this.exportData();
        });

        document.getElementById('importDataBtn').addEventListener('click', () => {
            this.importData();
        });

        document.getElementById('clearHistoryBtn').addEventListener('click', () => {
            this.clearHistory();
        });

        // 浏览路径按钮
        document.getElementById('browsePathBtn').addEventListener('click', () => {
            this.browseDownloadPath();
        });

        // 监听表单变化
        this.bindFormEvents();

        // 监听存储变化
        chrome.storage.onChanged.addListener((changes, namespace) => {
            this.handleStorageChange(changes, namespace);
        });
    }

    /**
     * 绑定表单事件
     */
    bindFormEvents() {
        // 监听所有表单控件的变化
        const formControls = document.querySelectorAll('input, select, textarea');
        formControls.forEach(control => {
            control.addEventListener('change', () => {
                this.markAsChanged();
            });

            control.addEventListener('input', () => {
                this.markAsChanged();
            });
        });

        // 监听格式标签的变化
        document.querySelectorAll('.format-tag input[type="checkbox"]').forEach(checkbox => {
            checkbox.addEventListener('change', () => {
                this.markAsChanged();
            });
        });
    }

    /**
     * 切换设置区域
     */
    switchSection(sectionId) {
        // 更新导航状态
        document.querySelectorAll('.nav-item').forEach(item => {
            item.classList.remove('active');
        });
        document.querySelector(`[data-section="${sectionId}"]`).classList.add('active');

        // 更新内容区域
        document.querySelectorAll('.settings-section').forEach(section => {
            section.classList.remove('active');
        });
        document.getElementById(sectionId).classList.add('active');

        // 更新URL哈希
        window.location.hash = sectionId;
    }

    /**
     * 加载设置
     */
    async loadSettings() {
        try {
            const response = await chrome.runtime.sendMessage({
                action: 'getSettings'
            });

            if (response.success) {
                currentSettings = response.data;
                this.populateForm(currentSettings);
                console.log('设置加载成功');
            } else {
                throw new Error(response.error || '加载设置失败');
            }
        } catch (error) {
            console.error('加载设置失败:', error);
            this.showError('加载设置失败: ' + error.message);
        }
    }

    /**
     * 填充表单
     */
    populateForm(settings) {
        // 常规设置
        document.getElementById('theme').value = settings.theme || 'light';
        document.getElementById('language').value = settings.language || 'zh-CN';
        document.getElementById('showNotifications').checked = settings.showNotifications !== false;
        document.getElementById('autoScan').checked = settings.autoScan !== false;

        // 下载设置
        document.getElementById('downloadPath').value = settings.downloadPath || 'downloads';
        document.getElementById('filenamePattern').value = settings.filenamePattern || '{filename}';
        document.getElementById('maxConcurrent').value = settings.maxConcurrent || 3;
        document.getElementById('maxFileSize').value = (settings.maxFileSize || 100 * 1024 * 1024) / (1024 * 1024);

        // 高级设置
        document.getElementById('enableLogging').checked = settings.enableLogging || false;
        document.getElementById('saveDownloadHistory').checked = settings.saveDownloadHistory !== false;
        document.getElementById('maxHistoryItems').value = settings.maxHistoryItems || 1000;

        // 文件格式设置
        this.populateFormatTags('imageFormats', settings.supportedImageFormats || ['jpg', 'jpeg', 'png', 'gif', 'webp']);
        this.populateFormatTags('videoFormats', settings.supportedVideoFormats || ['mp4', 'webm']);

        // 重置未保存状态
        hasUnsavedChanges = false;
        this.updateSaveButton();
    }

    /**
     * 填充格式标签
     */
    populateFormatTags(containerId, formats) {
        const container = document.getElementById(containerId);
        const checkboxes = container.querySelectorAll('input[type="checkbox"]');

        checkboxes.forEach(checkbox => {
            checkbox.checked = formats.includes(checkbox.value);
        });
    }

    /**
     * 收集表单数据
     */
    collectFormData() {
        const settings = {
            // 常规设置
            theme: document.getElementById('theme').value,
            language: document.getElementById('language').value,
            showNotifications: document.getElementById('showNotifications').checked,
            autoScan: document.getElementById('autoScan').checked,

            // 下载设置
            downloadPath: document.getElementById('downloadPath').value,
            filenamePattern: document.getElementById('filenamePattern').value,
            maxConcurrent: parseInt(document.getElementById('maxConcurrent').value) || 3,
            maxFileSize: (parseInt(document.getElementById('maxFileSize').value) || 100) * 1024 * 1024,

            // 高级设置
            enableLogging: document.getElementById('enableLogging').checked,
            saveDownloadHistory: document.getElementById('saveDownloadHistory').checked,
            maxHistoryItems: parseInt(document.getElementById('maxHistoryItems').value) || 1000,

            // 文件格式设置
            supportedImageFormats: this.collectFormatTags('imageFormats'),
            supportedVideoFormats: this.collectFormatTags('videoFormats')
        };

        return settings;
    }

    /**
     * 收集格式标签
     */
    collectFormatTags(containerId) {
        const container = document.getElementById(containerId);
        const checkboxes = container.querySelectorAll('input[type="checkbox"]:checked');
        return Array.from(checkboxes).map(checkbox => checkbox.value);
    }

    /**
     * 保存设置
     */
    async saveSettings() {
        try {
            const newSettings = this.collectFormData();

            const response = await chrome.runtime.sendMessage({
                action: 'updateSettings',
                settings: newSettings
            });

            if (response.success) {
                currentSettings = newSettings;
                hasUnsavedChanges = false;
                this.updateSaveButton();
                this.showSuccess('设置保存成功');
                console.log('设置保存成功');
            } else {
                throw new Error(response.error || '保存设置失败');
            }
        } catch (error) {
            console.error('保存设置失败:', error);
            this.showError('保存设置失败: ' + error.message);
        }
    }

    /**
     * 重置设置
     */
    async resetSettings() {
        if (!confirm('确定要重置所有设置吗？此操作不可撤销。')) {
            return;
        }

        try {
            const response = await chrome.runtime.sendMessage({
                action: 'resetSettings'
            });

            if (response.success) {
                await this.loadSettings();
                this.showSuccess('设置已重置为默认值');
                console.log('设置重置成功');
            } else {
                throw new Error(response.error || '重置设置失败');
            }
        } catch (error) {
            console.error('重置设置失败:', error);
            this.showError('重置设置失败: ' + error.message);
        }
    }

    /**
     * 导出数据
     */
    async exportData() {
        try {
            const response = await chrome.runtime.sendMessage({
                action: 'exportData'
            });

            if (response.success) {
                const data = response.data;
                const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
                const url = URL.createObjectURL(blob);

                const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
                const filename = `download-manager-backup-${timestamp}.json`;

                chrome.downloads.download({
                    url: url,
                    filename: filename,
                    saveAs: true
                });

                setTimeout(() => URL.revokeObjectURL(url), 1000);
                this.showSuccess('数据导出成功');
                console.log('数据导出成功');
            } else {
                throw new Error(response.error || '导出数据失败');
            }
        } catch (error) {
            console.error('导出数据失败:', error);
            this.showError('导出数据失败: ' + error.message);
        }
    }

    /**
     * 导入数据
     */
    importData() {
        const fileInput = document.getElementById('importFileInput');
        fileInput.click();

        fileInput.addEventListener('change', async (e) => {
            const file = e.target.files[0];
            if (!file) return;

            try {
                const text = await file.text();
                const data = JSON.parse(text);

                if (!data.version || !data.settings) {
                    throw new Error('无效的数据格式');
                }

                const response = await chrome.runtime.sendMessage({
                    action: 'importData',
                    data: data
                });

                if (response.success) {
                    await this.loadSettings();
                    this.showSuccess('数据导入成功');
                    console.log('数据导入成功');
                } else {
                    throw new Error(response.error || '导入数据失败');
                }
            } catch (error) {
                console.error('导入数据失败:', error);
                this.showError('导入数据失败: ' + error.message);
            }

            // 清理文件输入
            fileInput.value = '';
        });
    }

    /**
     * 清空历史
     */
    async clearHistory() {
        if (!confirm('确定要清空所有下载历史吗？此操作不可撤销。')) {
            return;
        }

        try {
            const response = await chrome.runtime.sendMessage({
                action: 'clearDownloadHistory'
            });

            if (response.success) {
                this.showSuccess('下载历史已清空');
                console.log('下载历史清空成功');
            } else {
                throw new Error(response.error || '清空历史失败');
            }
        } catch (error) {
            console.error('清空历史失败:', error);
            this.showError('清空历史失败: ' + error.message);
        }
    }

    /**
     * 浏览下载路径
     */
    browseDownloadPath() {
        // Chrome扩展无法直接访问文件系统
        // 这里可以显示一个提示或打开一个输入对话框
        const path = prompt('请输入下载路径:', document.getElementById('downloadPath').value);
        if (path !== null) {
            document.getElementById('downloadPath').value = path;
            this.markAsChanged();
        }
    }

    /**
     * 更新存储使用情况
     */
    async updateStorageInfo() {
        try {
            const response = await chrome.runtime.sendMessage({
                action: 'getStorageUsage'
            });

            if (response.success) {
                const usage = response.data;
                document.getElementById('storageFill').style.width = `${usage.percentage}%`;
                document.getElementById('storageText').textContent = usage.bytesUsedFormatted + ' / 5 MB';
            }
        } catch (error) {
            console.error('获取存储使用情况失败:', error);
        }
    }

    /**
     * 处理存储变化
     */
    handleStorageChange(changes, namespace) {
        if (namespace === 'sync' && changes.settings) {
            console.log('设置已更新');
            this.loadSettings();
        }
    }

    /**
     * 标记为已更改
     */
    markAsChanged() {
        hasUnsavedChanges = true;
        this.updateSaveButton();
    }

    /**
     * 更新保存按钮状态
     */
    updateSaveButton() {
        const saveBtn = document.getElementById('saveBtn');
        saveBtn.disabled = !hasUnsavedChanges;
        saveBtn.textContent = hasUnsavedChanges ? '保存设置*' : '保存设置';
    }

    /**
     * 显示成功消息
     */
    showSuccess(message) {
        this.showNotification(message, 'success');
    }

    /**
     * 显示错误消息
     */
    showError(message) {
        this.showNotification(message, 'error');
    }

    /**
     * 显示通知
     */
    showNotification(message, type = 'info') {
        // 创建通知元素
        const notification = document.createElement('div');
        notification.className = `notification notification-${type}`;
        notification.textContent = message;

        // 设置样式
        Object.assign(notification.style, {
            position: 'fixed',
            top: '20px',
            right: '20px',
            padding: '12px 20px',
            borderRadius: '8px',
            color: 'white',
            fontWeight: '500',
            zIndex: '10000',
            animation: 'slideIn 0.3s ease',
            maxWidth: '300px',
            wordWrap: 'break-word'
        });

        // 设置背景色
        if (type === 'success') {
            notification.style.backgroundColor = '#4CAF50';
        } else if (type === 'error') {
            notification.style.backgroundColor = '#f44336';
        } else {
            notification.style.backgroundColor = '#2196F3';
        }

        // 添加到页面
        document.body.appendChild(notification);

        // 自动移除
        setTimeout(() => {
            notification.style.animation = 'slideOut 0.3s ease';
            setTimeout(() => {
                if (notification.parentNode) {
                    notification.parentNode.removeChild(notification);
                }
            }, 300);
        }, 3000);
    }
}

// 创建设置页面管理器实例
const optionsManager = new OptionsManager();

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    optionsManager.init();

    // 处理URL哈希
    const hash = window.location.hash.slice(1);
    if (hash) {
        const navItem = document.querySelector(`[data-section="${hash}"]`);
        if (navItem) {
            optionsManager.switchSection(hash);
        }
    }
});

// 添加CSS动画
const style = document.createElement('style');
style.textContent = `
  @keyframes slideIn {
    from {
      transform: translateX(100%);
      opacity: 0;
    }
    to {
      transform: translateX(0);
      opacity: 1;
    }
  }
  
  @keyframes slideOut {
    from {
      transform: translateX(0);
      opacity: 1;
    }
    to {
      transform: translateX(100%);
      opacity: 0;
    }
  }
`;
document.head.appendChild(style); 